package com.excel.analyze.service;

import cn.hutool.core.util.IdUtil;
import com.excel.analyze.dto.ResponseResult;
import com.excel.analyze.util.ExcelUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author duanboyao
 * @classname ExcelService
 * @date 2025/2/26 15:59
 * @description TODO
 */
@Service
public class ExcelService {

    public ResponseResult<List<String>> analyzeExcel(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
                return ResponseResult.error("仅支持Excel文件上传");
            }

            List<Map<String, String>> bigTypeAndIds = new ArrayList<>();
            List<String> sqls = new ArrayList<>();
            Set<String> bigTypes = new HashSet<>();

            List<List<String>> data = ExcelUtil.readExcel(file);

            data.forEach(row -> bigTypes.add(row.get(3)));


            bigTypes.forEach(bigType -> {
                Map<String, String> bigSql = new HashMap<>();

                String id = IdUtil.simpleUUID();

                bigSql.put(bigType, id);
                bigTypeAndIds.add(bigSql);

                sqls.add("INSERT INTO BDAOSC_ERROR_TYPE (ID, PID, NAME) VALUES ('" + id + "', '-1', '" + bigType + "');");
            });

            data.forEach(row -> {
                bigTypeAndIds.forEach(bigTypeAndId -> {
                    String s = bigTypeAndId.get(row.get(3));
                    if (s != null) {
                        sqls.add("INSERT INTO BDAOSC_ERROR_TYPE (ID, PID, CODE, NAME, \"DESC\") VALUES ('" + IdUtil.simpleUUID() + "', '" + s + "', '" + row.get(0) + "', '" + row.get(2) + "', '" + row.get(1) + "');");
                    }
                });

            });

            int size1 = bigTypeAndIds.size();
            System.out.println("共生成" + size1 + "条大类sql");
            int size = sqls.size();
            System.out.println("共生成" + size + "条sql");

            return ResponseResult.success(sqls);

        } catch (Exception e) {
            return ResponseResult.error("解析失败: " + e.getMessage());
        }
    }
}
